package br.net.woodstock.tickettoride.vaadin.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.net.woodstock.rockframework.domain.spring.ContextHelper;
import br.net.woodstock.tickettoride.api.access.UserService;
import br.net.woodstock.tickettoride.api.manager.ApplicationService;
import br.net.woodstock.tickettoride.api.manager.CertificateService;
import br.net.woodstock.tickettoride.api.manager.TicketService;
import br.net.woodstock.tickettoride.orm.User;
import br.net.woodstock.tickettoride.vaadin.web.security.LogonView;

import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.HttpServletRequestListener;
import com.vaadin.ui.Window;

public class TicketToRideApplication extends Application implements HttpServletRequestListener {

	private static final long							serialVersionUID	= -6992584830456830427L;

	private static ThreadLocal<TicketToRideApplication>	instance			= new ThreadLocal<TicketToRideApplication>();

	private ViewManager									viewManager;

	private Window										window;

	public TicketToRideApplication() {
		super();
		TicketToRideApplication.instance.set(this);
	}

	@Override
	public void init() {
		this.window = new Window("Ticket To Ride");
		this.setMainWindow(this.window);

		this.viewManager = new ViewManager(this.window);
		this.toLogin();
	}

	public void toLogin() {
		LogonView logon = new LogonView();
		this.viewManager.switchBody(logon);
	}

	public void doLogout() {
		LogonView logon = new LogonView();
		this.viewManager.switchBody(logon);
		this.viewManager.switchHeader(null);
		this.setUser(null);
		this.toLogin();
	}

	public void executeLogin(final String login, final String password) {
		User user = this.getUserService().getByLoginPassword(login, password);
		if (user != null) {
			this.setUser(user);
			this.viewManager.switchBody(new IndexView());
			this.viewManager.switchHeader(new MenuView());
		}
	}

	public ViewManager getViewManager() {
		return this.viewManager;
	}

	public Window getWindow() {
		return this.window;
	}

	public ApplicationService getApplicationService() {
		return ContextHelper.getInstance().getObject(ApplicationService.class);
	}

	public CertificateService getCertificateService() {
		return ContextHelper.getInstance().getObject(CertificateService.class);
	}

	public TicketService getTicketService() {
		return ContextHelper.getInstance().getObject(TicketService.class);
	}

	public UserService getUserService() {
		return ContextHelper.getInstance().getObject(UserService.class);
	}

	@Override
	public void onRequestStart(final HttpServletRequest request, final HttpServletResponse response) {
		TicketToRideApplication.instance.set(this);
	}

	@Override
	public void onRequestEnd(final HttpServletRequest request, final HttpServletResponse response) {
		TicketToRideApplication.instance.remove();
	}

	public static TicketToRideApplication getInstance() {
		return TicketToRideApplication.instance.get();
	}

}
